﻿using System;
using System.Data;

namespace Nardax.Data
{
    /// <summary>
    /// A set of extensions designed for use with output parameters. After calling procedure with output parameters you often want to get the value
    /// as a specific type and these extensions are designed specifically to support that scenario.
    /// </summary>
    public static class IDataParameterExtensions
    {
        /// <summary>
        /// Gets the value of the parameter as a specific type. If the value of the parameter is DBNull the default of the type specified is returned.
        /// </summary>
        public static T GetValue<T>(this IDataParameter parameter)
        {
            if (typeof(T).IsEnum)
            {
                return (T)Enum.Parse(typeof(T), parameter.GetValue<String>());
            }

            return (T)Convert.ChangeType(parameter.Value, typeof(T));
        }

        /// <summary>
        /// Get the value of the parameter as a nullable type. if the value of the paramter is DBNull the value returned is null.
        /// </summary>
        public static T? GetNullableValue<T>(this IDataParameter parameter) where T : struct
        {
            if (parameter.Value == DBNull.Value)
            {
                return new T?();
            }

            if (typeof(T).IsEnum)
            {
                return (T)Enum.Parse(typeof(T), parameter.GetValue<String>());
            }

            return (T?)Convert.ChangeType(parameter.Value, typeof(T));
        }
    }
}
